package com.web.combo.service.impl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.web.base.service.impl.BaseServiceImpl;
import com.web.combo.bean.TreeNode;
import com.web.combo.service.ComboboxService;

public class ComboboxServiceImpl extends BaseServiceImpl implements ComboboxService {

	@Override
	public List<Map<String, Object>> getCombobox() throws SQLException, IOException {
		String sql = "select value as \"value\", text as \"text\" from combobox";
		return this.findAll(sql);
	}

	@Override
	public int getComboboxCount() throws SQLException, IOException {
		String sql = "select count(*) as \"count\" from combobox";
		Map<String, Object> count = this.findObject(sql);
		if (count != null && count.size() > 0) {
			return Integer.parseInt(count.get("count").toString());
		}

		return 0;
	}

	@Override
	public List<Map<String, Object>> getCombobox(int start, int limit) throws SQLException, IOException {
		String sql = "select value as \"value\", text as \"text\" from combobox";
		return this.findPagingList(sql, start, limit);
	}

	@Override
	public List<TreeNode> getCombotree(String id) throws SQLException, IOException {
		String sql = "select id as \"id\", text as \"text\","
		        + "		 case when exists (select id from combotree where pid = b.id) then 'false' else 'true' end \"leaf\""
		        + "  from combotree b where pid = ?";
		List<Map<String, Object>> list = this.findAll(sql, id);
		
		List<TreeNode> nodes = null;
		if (list != null && list.size() > 0) {
			nodes = new ArrayList<TreeNode>();
			
			for (Map<String, Object> map : list) {
				TreeNode node = new TreeNode();
				node.setId((String)map.get("id"));
				node.setText((String)map.get("text"));
				node.setLeaf(new Boolean((String)map.get("leaf")));
				if (node.getLeaf().booleanValue()) {
					node.setIconCls("");
				} else {
					node.setIconCls("");
				}
				
				nodes.add(node);
			}
		}
		
		return nodes;
	}

}
